import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 *
 * @author lenovo
 * @date 2018/10/31
 */
public class ServiceRegisterImpl implements ServiceRegister {

    CuratorFramework curatorFramework=null;

    private final String REGISTER_ROOT="/register";

    {

        curatorFramework= CuratorFrameworkFactory.builder()
                .connectString("172.30.1.172:2181")
                .sessionTimeoutMs(5000)
                .retryPolicy(
                        new ExponentialBackoffRetry(100,10)
                ).build();

        curatorFramework.start();
    }

    @Override
    public void register(String serviceName, String serviceAddress) {
        String servicePath = REGISTER_ROOT + "/" + serviceName;
        try {

            if (curatorFramework.checkExists().forPath(servicePath) == null) {

                curatorFramework.create()
                        .creatingParentsIfNeeded()
                        .withMode(CreateMode.PERSISTENT)
                        .forPath(servicePath);
            }

            String addressPath = servicePath + "/" + serviceAddress;
            curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(addressPath);
            System.out.println("节点注册成功：" + addressPath);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String [] args){
        ServiceRegister serviceRegister=new ServiceRegisterImpl();
        serviceRegister.register("waiter","10.1.7.139:8080");
//        serviceRegister.register("services-A","10.1.7.140:8080");
    }

}
